<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>战略目标</el-breadcrumb-item>
      <el-breadcrumb-item>战略目标信息列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加任务按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addTeskDialogVisible = true">添加任务</el-button>
        </el-col>
      </el-row>

      <!-- 任务列表区域 -->
      <el-table :data="tesklist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <el-table
    :data="tableData"
    stripe
    border
    style="width: 100%">
    <el-table-column
      prop="date"
      label="日期"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="地址">
    </el-table-column>
  </el-table> -->
            <el-row>
              <el-col :span="18" class="bg-purple">单位名称</el-col>
              <el-col :span="2" class="bg-purple">是否完成任务</el-col>
              <el-col :span="2" class="bg-purple">分数</el-col>
              <el-col :span="2" class="bg-purple">操作</el-col>
            </el-row>
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.appraiseUnits" :key="i1">
              <!-- 渲染一级权限 -->
              <el-col :span="18" class="bg-purple">
                {{item1.deptmentname}}
              </el-col>
              <el-col :span="2" class="bg-purple">
                <el-tag v-if="item1.state===1" type="danger">未完成</el-tag>
                <el-tag v-else-if="item1.state===2" type="success">已完成</el-tag>
              </el-col>
              <el-col :span="2" class="bg-purple">
                {{item1.state}}
              </el-col>
              <el-col :span="2" class="bg-purple">
                查看详情
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row.appraiseUnits}}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="发布时间" prop="createTime" width="200px">
          <template slot-scope="scope">
            {{scope.row.createTime | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditTeskDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeTeskById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[10, 10, 15, 20]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加任务的对话框 -->
    <el-dialog title="添加任务" :visible.sync="addTeskDialogVisible" width="50%" @close="addTeskDialogClosed" :close-on-click-modal="false">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTeskDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTesk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改任务的对话框 -->
    <el-dialog title="修改任务" :visible.sync="editTeskDialogVisible" width="50%" @close="editTeskDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editTeskDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editTeskInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      // 所有任务列表数据
      tesklist: [],
      // 控制分配权限对话框的显示与隐藏
      total: 0,
      setRightDialogVisible: false,
      // 添加任务对话框显示或隐藏
      addTeskDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
      addForm: {
        title: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ]
      },
      // 添加任务对话框显示或隐藏
      editTeskDialogVisible: false,
      editForm: {
        title: '',
        id: '',
        createTime: ''
      },
      // 修改表单的验证规则对象
      editFormRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getTesksList()
  },
  methods: {
    // 获取任务的列表
    async getTesksList() {
      const { data: res } = await this.$http.get('teskinfo', {
        params: this.queryInfo
      })
      // console.log('获取任务的列表')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取任务列表失败！')
      }
      this.tesklist = res.data.items
      this.total = res.data.total
      // console.log('tesklist简化')
      // console.log(this.tesklist)
    },
    addTesk() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('tesk', this.addForm)
        console.log(res)
        this.$message.success('添加任务成功！')
        // 隐藏添加用户的对话框
        this.addTeskDialogVisible = false
        // 重新获取用户列表数据
        this.getTesksList()
      })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getTesksList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      // console.log(this.queryInfo)
      this.getTesksList()
    },
    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }

      // this.getTesksList()
      role.children = res.data
    },
    async showEditTeskDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('tesks/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('查询任务信息失败！')
      }
      console.log('显示单条任务信息')
      console.log(res.data)

      this.editForm = res.data
      console.log(this.editForm)
      this.editTeskDialogVisible = true
    },
    // 监听修改任务对话框的关闭事件
    editTeskDialogClosed() {
      this.$refs.editFormRef.clearValidate()
    },
    // 修改任务信息并提交
    editTeskInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        console.log(this.editForm)
        const { data: res } = await this.$http.put(
          'tesks/' + this.editForm.id,
          {
            title: this.editForm.title
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }

        // 关闭对话框
        this.editTeskDialogVisible = false
        // 刷新数据列表
        this.getTesksList()
        // 提示修改成功
        this.$message.success('更新任务信息成功！')
      })
    },
    // 根据Id删除对应的任务信息
    async removeTeskById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该任务, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('tesks/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      this.getTesksList()
    },
    // 展示分配权限的对话框
    // async showSetRightDialog(role) {
    //   this.roleId = role.id
    //   // 获取所有权限的数据
    //   const { data: res } = await this.$http.get('rights/tree')

    //   if (res.meta.status !== 200) {
    //     return this.$message.error('获取权限数据失败！')
    //   }

    //   // 把获取到的权限数据保存到 data 中
    //   this.rightslist = res.data
    //   console.log(this.rightslist)

    //   // 递归获取三级节点的Id
    //   this.getLeafKeys(role, this.defKeys)

    //   this.setRightDialogVisible = true
    // },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听添加任务对话框的关闭事件
    addTeskDialogClosed() {
      this.$refs.addFormRef.resetFields()
      // this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }

      this.$message.success('分配权限成功！')
      this.getTesksList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-col {
  margin: 0px;
  padding: 10px 0;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
// .bg-purple{
//   background: purple;
//   display: flex;
//   align-items: center;
// }
</style>
